package com.ea.admin.service.impl;

import com.ea.admin.service.ApplicationConfigService;
import com.ea.common.result.BizException;
import com.ea.common.result.ErrorCode;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.Map;

@Service
public class ApplicationConfigServiceImpl implements ApplicationConfigService {

    @Override
    public Map<String, Object> getDatabaseConfig(String ymlName, String path) {
        try {
            ApplicationConfigServiceImpl.class.getClassLoader().getResource(ymlName).getPath();
            Yaml yaml = new Yaml();
            String rootPath = getRootPath();
            FileInputStream fileInputStream = new FileInputStream(rootPath + File.separator + path + File.separator + ymlName);
            Map<String, Object> yamlMap = yaml.load(fileInputStream);
            Map<String, Object> spring = (Map<String, Object>) yamlMap.get("spring");
            Map<String, Object> datasource = (Map<String, Object>) spring.get("datasource");
            return datasource;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException(ErrorCode.SYSTEM_ERROR_APPLICATION_ERROR);
        }
    }

    public void saveDatabaseConfig(Map<String, Object> datasource, String src) {
        try {
            ApplicationConfigServiceImpl.class.getClassLoader().getResource("application.yaml").getPath();
            Yaml yaml = new Yaml();
            FileWriter fileWriter;
            FileInputStream fileInputStream = new FileInputStream(src);
            Map<String, Object> yamlMap = yaml.load(fileInputStream);
            fileWriter = new FileWriter(src);
            // 用yaml方法把map结构格式化为yaml文件结构
            // 重新写入yaml文件
            fileWriter.write(yaml.dumpAsMap(yamlMap));
            // 刷新
            fileWriter.flush();
            // 关闭流
            fileWriter.close();
            fileInputStream.close();
        } catch (Exception e) {
            throw new BizException(ErrorCode.SYSTEM_ERROR_APPLICATION_ERROR);
        }
    }

    public String getRootPath() {
        ApplicationHome h = new ApplicationHome(getClass());
        return h.getDir().getPath();
    }
}
